import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.OperationClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.MessageContext;
import org.dom4j.*;

/**
 *
 * @author Grillo
 */
public class TestWS extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            //Genero l'header della pagina
            createHeader(out);

            boolean call = request.getParameter("call")!=null ? Boolean.parseBoolean(request.getParameter("call")) : false;
            Integer matricola = request.getParameter("matricola")!=null ? Integer.parseInt(request.getParameter("matricola")) : 0;
            String tipo_utente = request.getParameter("user")!=null ? request.getParameter("user") : "";

            if(call) {
                //chiamo il servizio
                String result = "";
                if(!matricola.equals(0) && (tipo_utente.equalsIgnoreCase("ST") || tipo_utente.equalsIgnoreCase("DO")))
                    result = callWS(matricola, tipo_utente).toString();
                else
                    result = callWS().toString();

                result = result.replace("&lt;", "<");
                result = result.replace("&gt;", ">");
                Document d = DocumentHelper.parseText(result);

                List list = d.selectNodes("//esame");

                //elenco tutti gli esami
                out.println("<br/><p><a href=\"javascript:history.go(-1);\">Torna alla pagina precedente</a></p>");
                out.println("<table id=\"tabella\">");
                out.println("<th>Nome corso</th><th>Descrizione</th><th>Crediti</th><th>Docente</th>");
                for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                    Element el = (Element) iter.next();
                    out.println("<tr><td>" + el.selectSingleNode("nome").getText() + "</td><td>" + el.selectSingleNode("descrizione").getText() +
                        "</td><td>" + el.selectSingleNode("crediti").getText() + "</td><td>" + el.selectSingleNode("docente").getText() + "</td></tr>");
                }
                out.println("</table>");
            } else {
                //visualizzo il form
                out.println("<form action=\"testWS\" method=\"post\"><input type=\"hidden\" name=\"call\" value=\"true\"/>");
                out.println("<br/><input type=\"submit\" value=\"getListaEsami\" name=\"action\"/>()<br/></form>");
                out.println("<form action=\"testWS\"  method=\"post\"><input type=\"hidden\" name=\"call\" value=\"true\"/>");
                out.println("<br/><input type=\"submit\" value=\"getListaEsamiByMatricola\" name=\"action\"/>");
                out.println("(<input type=\"text\" name=\"matricola\"/>,<input type=\"text\" name=\"user\"/>)<br/></form>");
            }

            //Genero il footer della pagina
            out.println("</div><div id=\"footer\"><div class=\"bottom\">SIU - Sistema Informativo Universitario</div></div></div></body></html>");

        } catch(Exception e) {}
        finally {out.close();}
    }

    private SOAPEnvelope callWS() {
        try {
            //Inizializzo la chiamata al servizio
            ServiceClient client = new ServiceClient();
            OperationClient operationClient = client.createClient(ServiceClient.ANON_OUT_IN_OP);
            MessageContext outMsgCtx = new MessageContext();
            Options opts = outMsgCtx.getOptions();
            opts.setTo(new EndpointReference("http://localhost:8080/ListaEsamiWSService/ListaEsamiWS?wsdl"));
            opts.setAction("urn:getListaEsami");

            //creo la soap envelope
            SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
            SOAPEnvelope envelope = fac.getDefaultEnvelope();
            OMNamespace omNs = fac.createOMNamespace("http://webservices/", "xs");
            OMElement method = fac.createOMElement("getListaEsami", omNs);
            envelope.getBody().addChild(method);

            //richiamo il servizio richiesto
            outMsgCtx.setEnvelope(envelope);
            operationClient.addMessageContext(outMsgCtx);
            operationClient.execute(true);
            MessageContext inMsgtCtx = operationClient.getMessageContext("In");
            SOAPEnvelope result = inMsgtCtx.getEnvelope();
            return result;
        } catch(Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    private SOAPEnvelope callWS(Integer matricola, String tipo_utente) {
        try {
            //Inizializzo la chiamata al servizio
            ServiceClient client = new ServiceClient();
            OperationClient operationClient = client.createClient(ServiceClient.ANON_OUT_IN_OP);
            MessageContext outMsgCtx = new MessageContext();
            Options opts = outMsgCtx.getOptions();
            opts.setTo(new EndpointReference("http://localhost:8080/ListaEsamiWSService/ListaEsamiWS?wsdl"));
            opts.setAction("urn:getListaEsamiByMatricola");

            //creo la soap envelope con i parametri passati
            SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
            SOAPEnvelope envelope = fac.getDefaultEnvelope();
            OMNamespace omNs = fac.createOMNamespace("http://webservices/", "xs");
            OMNamespace omNs2 = fac.createOMNamespace("", "");
            OMElement method = fac.createOMElement("getListaEsamiByMatricola", omNs);
            OMElement matr = fac.createOMElement("matricola", omNs2);
            matr.setText(matricola.toString());
            OMElement user = fac.createOMElement("user", omNs2);
            user.setText(tipo_utente);
            method.addChild(matr);
            method.addChild(user);
            envelope.getBody().addChild(method);

            //richiamo il servizio richiesto
            outMsgCtx.setEnvelope(envelope);
            operationClient.addMessageContext(outMsgCtx);
            operationClient.execute(true);
            MessageContext inMsgtCtx = operationClient.getMessageContext("In");
            SOAPEnvelope result = inMsgtCtx.getEnvelope();
            return result;
        } catch(Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    private void createHeader(PrintWriter out) {
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
        out.println("<html><head><title>SIU - Sistema Informativo Universitario</title><link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\" /></head>");
		out.println("<body><div id=\"container\"><div id=\"striscia\"><div id=\"striscia-right\"></div></div>");
        out.println("<div id=\"header\"><div id=\"logo\"><img src=\"img/logo_scritta.png\" name=\"logo\" alt=\"SIU - home page\" border=\"0\"/></a></div></div><div id=\"content\">");
        out.println("<h1>Chiamata al WebService</h1>");
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}